Passed
Push — master ( 06bde6...6d2f62 )
by Paul
04:59
created

GLSR.Ajax.post   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
/** global: GLSR, jQuery */
2
;(function( x ) {
3
4
	'use strict';
5
6
	var Ajax = function( request, ev ) { // object
7
		this.event = ev || null;
8
		this.post = this.post_;
9
		this.request = request;
10
	};
11
12
	Ajax.prototype = {
13
		/** @return void */
14
		buildData_: function( el ) { // HTMLElement|null
15
			this.buildNonce_( el );
16
			return {
17
				action: GLSR.action,
18
				request: this.request,
19
			};
20
		},
21
22
		/** @return void */
23
		buildNonce_: function( el ) { // HTMLElement|null
24
			if( this.request.nonce )return;
25
			if( GLSR.nonce[this.request.action] ) {
26
				this.request.nonce = GLSR.nonce[this.request.action];
27
				return;
28
			}
29
			if( !el )return;
30
			this.request.nonce = el.closest( 'form' ).find( '#_wpnonce' ).val();
31
		},
32
33
		/** @return void */
34
		post_: function( callback ) { // function|void
35
			if( this.event ) {
36
				this.postFromEvent_( callback );
37
				return;
38
			}
39
			x.post( GLSR.ajaxurl, this.buildData_(), function( response ) {
40
				if( typeof callback !== 'function' )return;
41
				callback( response );
42
			});
43
		},
44
45
		/** @return void */
46
		postFromEvent_: function( callback ) { // Event, function|void
47
			this.event.preventDefault();
48
			var el = x( this.event.target );
49
			if( el.is( ':disabled' ))return;
50
			el.prop( 'disabled', true );
51
			x.post( GLSR.ajaxurl, this.buildData_( el ), function( response ) {
52
				if( typeof callback === 'function' ) {
53
					callback( response );
54
				}
55
				el.prop( 'disabled', false );
56
			});
57
		},
58
	};
59
60
	GLSR.Ajax = Ajax;
61
})( jQuery );
62